package com.joysuch.wwyt.bp.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.joysuch.wwyt.bp.constant.AppNotifyContentPre;
import com.joysuch.wwyt.bp.entity.BpInspectionNotifyConfig;
import com.joysuch.wwyt.bp.job.bean.ToSendUser;
import com.joysuch.wwyt.bp.mapper.BpInspectionMapper;
import com.joysuch.wwyt.bp.service.BpInspectionNotifyConfigService;
import com.joysuch.wwyt.common.entity.CommonBusinessNotice;
import com.joysuch.wwyt.common.entity.CommonIndexNotify;
import com.joysuch.wwyt.common.enums.AppBusinessNoticeTypes;
import com.joysuch.wwyt.common.enums.CommonIndexNotifyTypes;
import com.joysuch.wwyt.common.repository.CommonIndexNotifyDao;
import com.joysuch.wwyt.common.service.CommonBusinessNoticeService;
import com.joysuch.wwyt.core.common.util.DateTimeUtil;
import com.joysuch.wwyt.core.common.util.JsonUtil;
import com.joysuch.wwyt.core.enums.UserRoleTypes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 全员督察提醒
 *
 * @author A
 * 2022-07-06
 */
@Slf4j
@Component
public class BpInspectionNotifyJob {

    @Resource
    private BpInspectionMapper bpInspectionMapper;
    @Resource
    private BpInspectionNotifyConfigService service;
    @Resource
    private CommonIndexNotifyDao commonIndexNotifyDao;
    @Resource
    private CommonBusinessNoticeService commonBusinessNoticeService;

    @Scheduled(cron = "0 0 5 * * *")
    public void runTask() {
        try {
            log.info("全员督察任务提醒开始...");
            LambdaQueryWrapper<BpInspectionNotifyConfig> query = new LambdaQueryWrapper<>();
            query.eq(BpInspectionNotifyConfig::getDeleteFlag, "0");
            List<BpInspectionNotifyConfig> cfgs = service.list(query);
            cfgs.forEach(this::_notify);
            log.info("全员督察任务提醒结束...");
        } catch (Exception e) {
            log.error("全员督察提醒任务执行异常", e);
        }
    }

    private void _notify(BpInspectionNotifyConfig config) {
        try {
            String period = config.getPeriod();
            String notifyDate = config.getNotifyDate();
            Integer times = config.getTimes();
            Integer role = config.getRole();
            Long tenentId = config.getTenentId();
            String orgCode = config.getOrgCode();

            boolean checkSend = false;
            if ("每周一".equals(notifyDate)) {
                checkSend = LocalDate.now().getDayOfWeek().equals(DayOfWeek.MONDAY);
            } else if ("每月一号".equals(notifyDate)) {
                checkSend = LocalDate.now().getDayOfMonth() == 1;
            }

            log.info("配置 {} checkSend {}", JsonUtil.toJson(config), checkSend);

            if (checkSend) {
                Date startDate = null;
                Date endDate = null;
                if ("每月".equals(period)) {
                    startDate = DateTimeUtil.localDate2Date(DateTimeUtil.getFirstDayOfCurrentMonth());
                    endDate = DateTimeUtil.localDate2Date(DateTimeUtil.getLastDayOfCurrentMonth());
                } else if ("每季度".equals(period)) {
                    startDate = DateTimeUtil.localDate2Date(DateTimeUtil.getFirstDayOfCurrentQuarter());
                    endDate = DateTimeUtil.localDate2Date(DateTimeUtil.getLastDayOfCurrentQuarter());
                }
                endDate = new Date(endDate.getTime() + 86400000);
                List<ToSendUser> toSendUsers = bpInspectionMapper.selectToSendUsers(role, times, startDate, endDate, tenentId, orgCode);

                log.info("待通知用户列表{}", JsonUtil.toJson(toSendUsers));

                _sendNotify(role, period, times, toSendUsers);
            }

        } catch (Exception e) {
            log.error("全员督察提醒任务执行异常 " + JsonUtil.toJson(config), e);
        }
    }

    private void _sendNotify(Integer role, String period, Integer times, List<ToSendUser> users) {
        List<CommonIndexNotify> notifyList = new ArrayList<>();
        List<CommonBusinessNotice> commonBusinessNotices = new ArrayList<>();

        for (ToSendUser baseUser : users) {
            //提醒逻辑更改为证书提醒时间加上提前量后的提醒时间在当前时间之前的需要发送提醒消息,
            //为了防止重复生成提醒消息,以cert_user_id,和提醒时间以及提醒人员id,以及证书管理的类型(到期，复证),以及证书的过期日期为条件去查重,符合条件的不去生成通知
            CommonIndexNotify notify = new CommonIndexNotify();
            //因为是定时任务生成的通知，兼容提前量大于剩余时间的数据，提醒时间统一取当前时间
//            notify.setBusinessDate();
            //到期提醒日期
            notify.setRemindDate(LocalDate.now());
            //到期提醒时间
            notify.setRemindDateTime(LocalDateTime.now());

            notify.setType(CommonIndexNotifyTypes.INSPECT_TASK.getType());
            notify.setReadFlag(0);
            notify.setQueueOrNot(0);
            notify.setRemindedOrNot(0);
            //到期提醒日期
            notify.setRemindDate(LocalDate.now());
            //到期提醒时间
            notify.setRemindDateTime(LocalDateTime.now());
            //人员id
            notify.setUserId(baseUser.getUserId());
            //提醒message格式：张三[管理人员] 您本月应完成全员督察提报2次，当前已提报1次，剩余未提报1次。

            String message = String.format("%s[%s] 您%s应完成全员督察提报%d次，当前已提报%d次，剩余未提报%d次。",
                    baseUser.getUserName(), UserRoleTypes.getRoleNameByIndex(role), period.replace("每", "本"),
                    times, baseUser.getCount(), times - baseUser.getCount());

            notify.setTenentId(baseUser.getTenentId());
            notify.setOrgCode(baseUser.getOrgCode());
            notify.setCreateBy(null);
            notify.setUpdateBy(null);
            notify.setReadFlag(0);
            notify.setQueueOrNot(1);
            notify.setRemindedOrNot(1);
            notify.setEduCertUserId(baseUser.getUserId());
            notify.setNotifyMessage(message);

            notifyList.add(notify);

            CommonBusinessNotice notice = new CommonBusinessNotice();
            notice.setNoticeTitle(AppNotifyContentPre.TASK_NOTIFY);
            notice.setBusinessType(AppBusinessNoticeTypes.INVESTIGATE.getType());
            notice.setNoticeContent(message);
            notice.setNoticeUser(baseUser.getUserId());
            notice.setReaded("0");
            notice.setRefId(null);
            notice.setSendTime(new Date());

            notice.setTenentId(1L);
            notice.setCreateBy(9784L);
            notice.setUpdateBy(9784L);

            notice.setCreateTime(new Date());
            notice.setUpdateTime(new Date());
            notice.setDeleteFlag("0");

            commonBusinessNotices.add(notice);
        }

        if (notifyList.size() > 0) {
            commonIndexNotifyDao.saveAll(notifyList);
        }

        if (commonBusinessNotices.size() > 0) {
            commonBusinessNoticeService.saveBatch(commonBusinessNotices);
        }
    }

}
